<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <div class="filter-container">
            <el-form inline size="small">
                <el-form-item label="学生">
                    <el-input
                        v-model="searchQuery.studentName"
                        class="filter-item w-150"
                        readonly
                        :disabled="studentId > 0"
                        placeholder="请选择"
                        @click.native="filterSelectStudentVisible = true"
                        />
                </el-form-item>
                <el-form-item label="课程">
                    <el-input
                        v-model="searchQuery.courseName"
                        class="filter-item w-150"
                        readonly
                        :disabled="courseId > 0"
                        placeholder="请选择"
                        @click.native="filterSelectCourseVisible = true"
                        />
                </el-form-item>
                <el-form-item label="时间">
                    <el-date-picker
                        v-model="searchQuery.dateRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        class="filter-item w-250"
                        />
                </el-form-item>
                <el-form-item label="支付">
                    <el-select v-model="searchQuery.payStatus" placeholder="支付状态" class="filter-item w-100">
                        <el-option label="全部" :value="2" />
                        <el-option label="未支付" :value="0" />
                        <el-option label="已支付" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
                    <el-button type="danger" icon="el-icon-plus" @click="showDialog()">报课</el-button>
                </el-form-item>
            </el-form>
            <SelectStudent :visible.sync="filterSelectStudentVisible" @select="filterSelectStudent" />
            <SelectCourse :visible.sync="filterSelectCourseVisible" @select="filterSelectCourse" />
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <el-table :data="pageInfo.data" stripe border :loading="listLoading" style="width: 100%">
                <el-table-column prop="id" label="ID" width="50" />
                <el-table-column prop="student_name" label="姓名" width="120" />
                <el-table-column prop="course_name" label="课程名称" width="120" />
                <el-table-column prop="course_num" label="课时" width="50" />
                <el-table-column prop="send_num" label="赠送" width="50" />
                <el-table-column prop="surplus_num" label="剩余" width="50" />
                <el-table-column prop="valid_begin_date" label="有效期开始" width="100" />
                <el-table-column prop="valid_end_date" label="有效期结束" width="100" />
                <el-table-column prop="total_price" label="课程金额" />
                <el-table-column prop="pay_price" label="实际金额" />
                <el-table-column prop="discount_price" label="优惠金额" />
                <el-table-column prop="pay_status_text" label="支付状态" />
                <el-table-column prop="pay_type" label="支付方式" />
                <el-table-column prop="pay_no" label="支付单号" />
                <el-table-column prop="pay_time" label="支付时间" width="160" />
                <el-table-column prop="created_at" label="创建时间" width="160" />
                <el-table-column label="操作" width="140">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="showSign(scope.$index)">记录</el-button>
                        <el-button type="text" size="mini" @click="showDialog(scope.$index)">编辑</el-button>
                        <el-button type="text" size="mini" @click="handleDelete(scope.row)">退课</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageInfo.total>0" :total="pageInfo.total" :page.sync="pageInfo.current_page" :limit.sync="pageInfo.per_page" @pagination="getList" />
        </div>

        <!-- 新增/编辑对话框 -->
        <div class="dialog-container">
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :close-on-click-modal="false" width="900px">
                <el-form label-position="right" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="学生姓名">
                                <el-input v-model="temp.student_name" :disabled="studentId > 0" @click.native="selectStudentVisible = true" />
                            </el-form-item>
                            <el-form-item label="课程名称">
                                <el-input v-model="temp.course_name" :disabled="courseId > 0" readonly @click.native="selectCourseVisible = true" />
                            </el-form-item>
                            <el-form-item label="课程套餐">
                                <el-select v-model="temp.total_price" @change="changePackage">
                                    <el-option label="请选择" :value="0" />
                                    <el-option v-for="(item, index) in packages" :key="index" :value="item.package_price" :label="item.package_name + '/' + item.course_num + '节/' + item.package_price + '元'" />
                                </el-select>
                            </el-form-item>"
                            <el-form-item label="应付金额">
                                <el-input v-model="temp.total_price" disabled class="w-80" />
                                <label class="mx-5">优惠</label>
                                <el-input v-model="temp.discount_price" type="number" class="w-80" />
                                <label class="mx-5">实付</label>
                                <el-input v-model="temp.pay_price" disabled class="w-80" />
                            </el-form-item>
                            <el-form-item label="课时">
                                <el-input v-model="temp.course_num" type="number" class="w-80" disabled />
                                <label class="mx-5">赠送</label>
                                <el-input v-model="temp.send_num" type="number" class="w-80" />
                                <label class="mx-5">已销</label>
                                <el-input v-model="temp.learned_num" type="number" placeholder="请输入已销课" class="w-80" />
                            </el-form-item>
                            <el-form-item label="有效日期">
                                <div class="flex">
                                    <el-date-picker v-model="temp.valid_begin_date" type="date" placeholder="选择开始日期" value-format="yyyy-MM-dd" class="w-150" />
                                    <el-select v-model="temp.valid_time_len" class="w-150 ml-5" placeholder="请选择有效时长">
                                        <el-option label="永久" :value="0" />
                                        <el-option label="1个月" :value="1" />
                                        <el-option label="3个月" :value="3" />
                                        <el-option label="半年" :value="6" />
                                        <el-option label="1年" :value="12" />
                                        <el-option label="2年" :value="24" />
                                    </el-select>
                                </div>
                            </el-form-item>"
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="支付方式">
                                <el-select v-model="temp.pay_type" placeholder="请选择支付方式">
                                    <el-option label="请选择" value="" />
                                    <el-option label="微信" value="微信" />
                                    <el-option label="支付宝" value="支付宝" />
                                    <el-option label="现金" value="现金" />
                                    <el-option label="转账" value="转账" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="支付状态">
                                <el-select v-model="temp.pay_status" placeholder="请选择支付状态">
                                    <el-option label="未支付" :value="0" />
                                    <el-option label="已支付" :value="1" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="支付时间">
                                <el-date-picker v-model="temp.pay_time" type="datetime" placeholder="选择支付时间" value-format="yyyy-MM-dd HH:mm:ss" />
                            </el-form-item>
                            <el-form-item label="支付流水">
                                <el-input v-model="temp.pay_no" placeholder="请输入支付流水号" />
                            </el-form-item>
                            <el-form-item label="备注">
                                <el-input v-model="temp.note" placeholder="请输入备注" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <SelectCourse :visible.sync="selectCourseVisible" @select="handleSelectCourse" />
                <SelectStudent :visible.sync="selectStudentVisible" @select="handleSelectStudent" />
                <div slot="footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit()">确认</el-button>
                </div>
            </el-dialog>
        </div>

        <course-signs ref="courseSigns" />
    </div>
</template>

<script>
    import Pagination from '@/components/Pagination' // 导入分页组件
    import SelectCourse from '../components/SelectCourse.vue'
    import SelectStudent from '../components/SelectStudent.vue'
    import CourseSigns from './components/course-signs.vue'
    import studentCourseApi from '@/api/student-course'
    import courseApi from '@/api/course'
    import { resetObject } from '@/utils'

    export default {
        name: 'StudentCourse',
        components: { Pagination, SelectCourse, SelectStudent, CourseSigns },
        data() {
            return {
                listLoading: true,
                dialogVisible: false, // 对话框的可见性
                dialogTitle: '新增报课', // 对话框标题
                filterSelectCourseVisible: false, // 筛选课程对话框
                filterSelectStudentVisible: false, // 筛选学生对话框
                selectCourseVisible: false,
                selectStudentVisible: false,
                studentId: 0,
                courseId: 0,
                packages: [],
                temp: { // 临时数据
                    id: 0,
                    student_id: 0, // 学生ID
                    student_name: '', // 学生姓名
                    course_id: 0, // 课程ID
                    course_name: '', // 课程名称
                    total_price: 0, // 课程金额
                    pay_price: 0, // 实际金额
                    discount_price: 0, // 优惠金额
                    course_num: 0, // 课时数量
                    send_num: 0,
                    learned_num: 0,
                    valid_begin_date: '', // 开始日期
                    valid_time_len: '', // 有效时长
                    pay_type: '', // 支付方式
                    pay_status: 0, // 支付状态
                    pay_time: '', // 支付时间
                    pay_no: '', // 支付流水号
                    note: ''
                },
                pageInfo: {
                    total: 0,
                    current_page: 1,
                    per_page: 10,
                    data: []
                },
                searchQuery: {
                    studentId: 0,
                    courseId: 0,
                    studentName: '',
                    courseName: '',
                    dateRange: null,
                    payStatus: 2
                }
            }
        },
        watch: {
            $route: {
                immediate: true,
                handler(route) {
                    const studentId = parseInt(route.query.studentId || 0)
                    const studentName = route.query.studentName || ''
                    const courseId = parseInt(route.query.courseId || 0)
                    const courseName = route.query.courseName || ''

                    this.studentId = studentId
                    this.courseId = courseId

                    // 用于新增时回显
                    this.temp.student_id = studentId
                    this.temp.course_id = courseId
                    this.temp.student_name = studentName
                    this.temp.course_name = courseName

                    // 用于搜索
                    this.searchQuery.courseName = courseName
                    this.searchQuery.studentName = studentName
                    this.searchQuery.studentId = studentId
                    this.searchQuery.courseId = courseId
                    this.getList()

                    if (this.courseId) {
                        courseApi.info(this.courseId).then(res => {
                            console.log('路由改变')
                            this.handleSelectCourse(res.data)
                        })
                    } else {
                        this.search()
                    }
                }
            },
            'temp.discount_price': {
                handler(newVal, oldVal) {
                    if (newVal !== oldVal) {
                        this.temp.pay_price = this.temp.total_price - newVal // 计算市场价格
                    }
                }
            }
        },
        created() {},
        methods: {
            search() {
               this.pageInfo.current_page = 1
               this.getList()
            },
            getList() {
                const dates = this.searchQuery.dateRange
                studentCourseApi.page({
                    page: this.pageInfo.current_page,
                    per_page: this.pageInfo.per_page,
                    student_id: this.searchQuery.studentId,
                    course_id: this.searchQuery.courseId,
                    pay_status: this.searchQuery.payStatus,
                    begin_date: dates ? dates[0] : '',
                    end_date: dates ? dates[1] : ''
                }).then(res => {
                    res.data.data.forEach(item => {
                        item.pay_status_text = item.pay_status === 0 ? '未支付' : '已支付'
                        item.surplus_num = (item.course_num + item.send_num) - item.learned_num
                    })
                    this.pageInfo = res.data
                })
            },
            filterSelectCourse(course) {
                this.searchQuery.courseId = course.id
                this.searchQuery.courseName = course.name
            },
            filterSelectStudent(student) {
                this.searchQuery.studentId = student.id
                this.searchQuery.studentName = student.name
            },
            handleSelectCourse(res) {
                if (this.temp.course_id !== res.id) {
                    this.temp.course_id = res.id // 更新课程ID
                    this.temp.course_name = res.name // 更新课程名称
                    // 重置课程金额
                    this.temp.total_price = 0 // 重置课程金额
                    this.temp.discount_price = 0 // 重置优惠金额
                    this.temp.pay_price = 0 // 重置实际金额
                    this.temp.course_num = 0 // 重置课时数量
                }
                this.packages = res.packages
                this.selectCourseVisible = false // 关闭选择课程对话框
            },
            handleSelectStudent(res) {
                this.temp.student_id = res.id // 更新学生ID
                this.temp.student_name = res.name // 更新学生姓名
            },
            showDialog(index) {
                this.dialogVisible = true
                if (typeof index === 'undefined') {
                    this.dialogTitle = '新增报课'
                    if (this.temp.id) {
                        resetObject(this.temp)
                    }
                } else {
                    this.temp = JSON.parse(JSON.stringify(this.pageInfo.data[index]))
                    this.dialogTitle = '编辑报课'
                    courseApi.info(this.temp.course_id).then(res => {
                        this.packages = res.data.packages
                    })
                }
            },
            handleSubmit() {
                studentCourseApi.save(this.temp).then(res => {
                    this.$message.success('保存成功')
                    this.dialogVisible = false
                    this.getList()
                })
            },
            handleDelete(item) {
                this.$confirm('确认删除该条数据吗？', '提示').then(() => {
                    studentCourseApi.delete(item.id).then(res => {
                        this.$message.success('删除成功')
                        this.getList()
                    })
                }).catch(() => {})
            },
            changePackage(price) {
                this.packages.forEach(item => {
                    if (item.package_price === price) {
                        this.temp.course_num = item.course_num
                        this.temp.total_price = item.package_price
                        this.temp.pay_price = this.temp.total_price - this.temp.discount_price // 计算市场价格
                    }
                })
            },
            showSign(index) {
                console.log(index)
                const course = this.pageInfo.data[index]
                this.$refs.courseSigns.show(course.student_id, course.course_id)
            }
        }
    }
</script>
